// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router/index'
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import axios from 'axios';

Vue.config.productionTip = false

Vue.use(ElementUI);
//设置axios的属性
axios.defaults.baseURL="http://localhost:8085";  //'/admingoods'
axios.defaults.withCredentials=true;//前端允许跨域

//路由守卫
// router.beforeEach((to, from, next) => {
//   var token=localStorage.getItem("token");
//   console.log('路由守卫===》',to,from,token)
//   var isAuthenticated=false; //标识是否登录，默认是未登录状态
//   if(token!=null){
//     isAuthenticated=true;
//   }
//   //如果未非登录页面，且是未登录状态
//   if (to.name !== 'login' && !isAuthenticated) {
//     if(to.name=='list')next()
//     else next({ name: 'login' });
//   }else next()
// })


//设置axios的拦截
//请求拦截
axios.interceptors.request.use(function (config) {
  //config请求对象
  // Do something before request is sent
  //获得token
  var token=localStorage.getItem("token");
  console.log("axios interceptor request===>",token);
  //如果非空，设置在请求头中
  if(token!=null){
    config.headers['token']=token;
  }
  return config;
}, function (error) {
  // Do something with request error
  return Promise.reject(error);
});

//响应拦截
axios.interceptors.response.use(function (response) {
  // Do something with response data
  console.log('axios response interceptor:',response);
  if(response.data.code==201){ //由后端返回的结果，code值是201，
    //跳转登录页面
    router.push('/login');
  }else if(response.data.code!=200){
    ElementUI.Message({
      message: response.data.msg,
      type: 'error'
    })
  }
  return response.data; //后端ResultMsg对象
  // return response;
}, function (error) {
  // Do something with response error
  return Promise.reject(error);
});

Vue.prototype.$axios=axios; //全局设置，设置为vue的属性


/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})
